using System;
using Castle.DynamicProxy;

namespace EntityAop.Interceptors.Support
{
    public static class InvocationHelper
    {
        public static Type GetTargetType(IInvocation invocation)
        {
            return GetInvocationTarget(invocation).GetType();
        }

        public static int GetInvocationTargetHashCode(IInvocation invocation)
        {
            return GetInvocationTarget(invocation).GetHashCode();
        }

        public static object GetInvocationTarget(IInvocation invocation)
        {
            if (invocation.InvocationTarget != null)
            {
                return invocation.InvocationTarget;
            }

            return GetTargetInvocationDirectlyFromProxy(invocation.Proxy);
        }

        public static object GetTargetInvocationDirectlyFromProxy(object proxy)
        {
            return proxy.GetType().GetField("__target").GetValue(proxy);
        }
    }
}